package com.yeyks.commonReference.append.mongodb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.yeyks.commonReference.append.mongodb.entity.CnRoomImageMongoEntity;
import com.yeyks.commonReference.append.mongodb.repository.CnRoomImageMongoRepository;
import com.yeyks.commonReference.append.mongodb.service.CnRoomImageMongoMongoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CnRoomImageMongoMongoServiceImpl implements CnRoomImageMongoMongoService {

    private final CnRoomImageMongoRepository cnRoomImageMongoRepository;

    @Override
    public void save(CnRoomImageMongoEntity cnRoomImageMongoEntity) {
        try {
            Optional<CnRoomImageMongoEntity> byId = cnRoomImageMongoRepository.findById(cnRoomImageMongoEntity.getRoomId());
            if (byId.isPresent()) {
                cnRoomImageMongoRepository.deleteById(cnRoomImageMongoEntity.getRoomId());
            }
            cnRoomImageMongoRepository.save(cnRoomImageMongoEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新mongo中的房间错误图片
     */
    @Override
    public Boolean updateErrorData() {
        try {
            List<CnRoomImageMongoEntity> cnRoomImageNews = Lists.newArrayList();
            List<CnRoomImageMongoEntity> cnRoomImageMongoEntities = cnRoomImageMongoRepository.findAll();
            for (CnRoomImageMongoEntity cnRoom : cnRoomImageMongoEntities) {
                cnRoomImageNews.add(new CnRoomImageMongoEntity(cnRoom.getHotelId(), cnRoom.getRoomId(), cnRoom.getImages()));
            }
            if (CollectionUtil.isNotEmpty(cnRoomImageNews)) {
                cnRoomImageMongoRepository.deleteAll();
            }
            cnRoomImageMongoRepository.saveAll(cnRoomImageNews);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public CnRoomImageMongoEntity get(String sourceId) {
        try {
            Optional<CnRoomImageMongoEntity> cnRoomImageMongoRepositoryById = cnRoomImageMongoRepository.findById(sourceId);
            if (cnRoomImageMongoRepositoryById.isPresent()) {
                return cnRoomImageMongoRepository.findById(sourceId).get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
